package com.jhgsys.internal.dict.controller;

import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.dict.entity.Dict;
import com.jhgsys.internal.dict.service.IDictService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务字典 Controller
 *
 * @author 张雨生
 * @date 2020-11-22 15:28:25
 */
@Slf4j
@Validated
@Controller
public class DictController extends BaseController {

    @Autowired
    private IDictService dictService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "dict")
    @RequiresPermissions("dict:view")
    public String dictIndex(){
        return FebsUtil.view("dict/dict/dictList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "dict/add")
    public String dictAdd() {
        return FebsUtil.view("dict/dict/dictEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "dict/update/{id}")
    public String dictUpdate(Model model, @PathVariable("id") String id) {
        model.addAttribute("dict", dictService.findDictById(id));
        return FebsUtil.view("dict/dict/dictEdit");
    }

    /**
     * 查询（所有）
     *
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @GetMapping("dict")
    @ResponseBody
    public FebsResponse getAllDicts(Dict dict) {
        return new FebsResponse().success().data(dictService.findDicts(dict));
    }

    @GetMapping("dictItem/{code}")
    @ResponseBody
    public FebsResponse getDictByCode(@PathVariable("code") String dictCode) {
        return new FebsResponse().success().data(dictService.findDictByCode(dictCode));
    }

    /**
     * 查询（分页）
     *
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @GetMapping("dict/list")
    @ResponseBody
    public FebsResponse dictList(QueryRequest request, Dict dict) {
        Map<String, Object> dataTable = getDataTable(this.dictService.findDicts(request, dict));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 新增 Dict
     *
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @Log("新增Dict")
    @PostMapping("dict/add")
    @ResponseBody
    public FebsResponse addDict(@RequestBody @Valid Dict dict) throws FebsException {
        try {
            this.dictService.createDict(dict);
            return new FebsResponse().success();
        } catch (RuntimeException e1) {
            String message = "新增字典失败!";
            log.error(message, e1);
            throw new FebsException(message);
        } catch (Exception e) {
            String message = "新增Dict失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 逻辑删除 Dict
     *
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @Log("逻辑删除Dict")
    @GetMapping("dict/delete/{id}")
    @ResponseBody
    public FebsResponse deleteDict(@PathVariable("id") String dictIds) throws FebsException {
        try {
            Dict dict = new Dict();
            this.dictService.deleteDict(dict, dictIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除Dict失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 物理删除 Dict
     *
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @Log("物理删除Dict")
    @GetMapping("dict/physicallyDelete/{id}")
    @ResponseBody
    public FebsResponse physicallyDeleteDict(@PathVariable("id") String dictIds) throws FebsException {
        try {
            this.dictService.physicallyDeleteDict(dictIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除Dict失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 修改 Dict
     *
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @Log("修改Dict")
    @PostMapping("dict/update")
    @ResponseBody
    public FebsResponse updateDict(@RequestBody @Valid Dict dict) throws FebsException {
        try {
            this.dictService.updateDict(dict);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改Dict失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 导出 Dict的excel
     *
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @PostMapping("dict/excel")
    @ResponseBody
    public void export(QueryRequest queryRequest, Dict dict, HttpServletResponse response) throws FebsException {
        try {
            List<Dict> dicts = this.dictService.findDicts(queryRequest, dict).getRecords();
            ExcelKit.$Export(Dict.class, response).downXlsx(dicts, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 修改字典状态
     * @param dict
     * @return
     * @throws FebsException
     */
    @Log("修改字典状态")
    @ResponseBody
    @PostMapping("dict/updateDictStatus")
    public FebsResponse updatePostStatus(Dict dict) throws FebsException {
        try {
            if(StringUtils.isBlank(dict.getDictId())){
                return new FebsResponse().fail().message("字典Id不能为空！");
            }
            if(StringUtils.isBlank(dict.getStatus())){
                return new FebsResponse().fail().message("字典状态不能为空！");
            }
            Dict updateDict = new Dict();
            updateDict.setDictId(dict.getDictId());
            updateDict.setStatus(dict.getStatus());
            updateDict.setUpdatedBy(getCurrentUser().getUserName());
            updateDict.setUpdatedTime(new Date());

            this.dictService.updateById(updateDict);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改字典状态失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }
}
